﻿using MSBuild = Microsoft.Build.Evaluation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sasa.QualityTools.CodeAnalysis.Common;
using System.IO;
using System.Diagnostics.CodeAnalysis;

namespace Sasa.QualityTools.CodeAnalysis.FxCopIntegrator.VisualStudio
{
    public class CppProject : Project
    {
        private IDictionary<string, string> properties;


        [SuppressMessage("Microsoft.Design", "CA1031")]
        public override string TargetDir
        {
            get
            {
                try
                {
                    return project.ConfigurationManager.ActiveConfiguration.Properties.Item("OutputPath").Value.ToString();
                }
                catch (Exception ex)
                {
                    Logger.Error(ex, "Failed to get the directory that is generated assembly of '{0}' project.", project.Name);
                    return null;
                }
            }
        }

        [SuppressMessage("Microsoft.Design", "CA1031")]
        public override string AssemblyPath
        {
            get
            {
                try
                {
                    EnsureLoadingMSBuildPrperties();
                    return Path.Combine(TargetDir, properties["TargetFileName"]);
                }
                catch (Exception ex)
                {
                    Logger.Error(ex, "Failed to get assembly path of '{0}' project.", project.Name);
                    return null;
                }
            }
        }

        public override bool IsSupportedCodeAnalysis
        {
            get
            {
                EnsureLoadingMSBuildPrperties();
                return !properties["CLRSupport"].Equals(Boolean.FalseString, StringComparison.OrdinalIgnoreCase);
            }
        }

        public override string NotSupportedReason
        {
            get
            {
                return (!IsSupportedCodeAnalysis) ? "This project is disabled CLR support." : null; ;
            }
        }


        public CppProject(EnvDTE.Project project)
            : base(project)
        {
        }


        private void EnsureLoadingMSBuildPrperties()
        {
            if (properties != null) return;

            Logger.Info("Loading project file '{0}'.", project.FullName);

            var p = new MSBuild.Project(project.FullName);
            properties = p.Properties.OrderBy(o => o.Name).ToDictionary(o => o.Name, o => o.EvaluatedValue);
            MSBuild.ProjectCollection.GlobalProjectCollection.UnloadProject(p);
        }
    }
}
